import { AnyAction, Reducer } from 'redux';
import { message } from 'antd';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';
import {
  queryPartTimeWageList,
  operSaveOrUpdate,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    saveOrUpdate: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'partTimeWageAllocationList',

  state: {
    dataInfo: {
      list: [],
      count: 0,
    },
    logsList: [],
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryPartTimeWageList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * saveOrUpdate({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operSaveOrUpdate, query);
      const data = fetchValidation(response);
      if (data) {
        message.success(query.id ? '更新成功' : '添加成功');
        yield data && put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        dataInfo: payload,
      };
    },
  },
};

export default Model;
